﻿using AutoMapper;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;

namespace Shared.AutoMapperHelper
{
    /// <summary>
    /// AutoMapper 扩展方法
    /// </summary>
    public static class AutoMapperExtensions
    {
        /// <summary>
        /// 使用AutoMapper
        /// </summary>
        /// <param name="service"></param>
        /// <returns></returns>
        public static IServiceCollection AddAutoMapperExt(this IServiceCollection services)
        {
            //程序自动从所有程序集中扫描 Profile 继承的类，并将其添加到配置中
            Type baseType = typeof(Contracts.IAutoMapperConfig);
            List<Type> list = new List<Type>();            
            GetAssemblies().ForEach(assemblie =>
            {
                //try 起来是因为 可能系统的一些 assemblie 执行 GetTypes 会异常.
                try
                {
                    list.AddRange(
                                assemblie.GetTypes()
                                         .Where(type => baseType.IsAssignableFrom(type)
                                                        && !type.IsAbstract
                                                        && !type.IsInterface)
                            );
                }
                catch (Exception ex)
                { }
            });
            return services.AddAutoMapper(list.ToArray());
        }

        /// <summary>
        /// 查找bin文件夹下的所有DLL,进行注册
        /// </summary>
        /// <returns></returns>
        private static List<Assembly> GetAssemblies()
        {
            List<Assembly> assemblies = new List<Assembly>();
            try
            {
                string[] files = Directory.GetFiles(AppContext.BaseDirectory, "*.dll");//得到文件
                foreach (string file in files)//循环文件
                {
                    try
                    {
                        var assembly = Assembly.LoadFrom(file);
                        assemblies.Add(assembly);
                    }
                    catch (Exception ex)
                    { }
                }
            }
            catch (Exception ex)
            { }
            return assemblies;
        }
    }
}
